<template>
  <el-container class="layout-container">
    <!-- 侧边栏 -->
    <el-aside :width="isCollapse ? '64px' : '200px'">
      <div class="logo" :class="{ 'logo-collapse': isCollapse }">
        <router-link to="/nav/home" class="back-to-nav">
          返回导航
        </router-link>
      </div>
      <el-menu
        :default-active="activeMenu"
        :router="true"
        :collapse="isCollapse"
        background-color="#304156"
        text-color="#bfcbd9"
        active-text-color="#409EFF"
        :unique-opened="true"
        @select="handleSelect"
      >
        <template v-for="menu in menus" :key="menu.id">
          <menu-item :menu="menu" />
        </template>
      </el-menu>
    </el-aside>

    <el-container>
      <!-- 头部 -->
      <el-header>
        <div class="header-left">
          <el-icon class="fold-btn" @click="toggleCollapse">
            <component :is="isCollapse ? 'Expand' : 'Fold'" />
          </el-icon>
          <breadcrumb />
        </div>
        <div class="header-right">
          <el-dropdown trigger="hover" @command="handleCommand">
            <span class="user-info">
              <el-avatar :size="32" class="user-avatar">
                {{ userInfo.nickname?.charAt(0)?.toUpperCase() }}
              </el-avatar>
              <span class="nickname">{{ userInfo.nickname }}</span>
              <el-icon class="el-icon--right"><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">
                  <el-icon><User /></el-icon>
                  个人中心
                </el-dropdown-item>
                <el-dropdown-item divided command="logout">
                  <el-icon><SwitchButton /></el-icon>
                  退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <!-- 主体内容 -->
      <el-main>
        <router-view />
      </el-main>
    </el-container>
  </el-container>

  <!-- 个人中心对话框 -->
  <el-dialog
    title="个人中心"
    v-model="profileDialogVisible"
    width="500px"
    append-to-body
  >
    <el-tabs v-model="activeTab">
      <!-- 基本信息 -->
      <el-tab-pane label="基本信息" name="info">
        <el-form
          ref="profileForm"
          :model="profileData"
          :rules="profileRules"
          label-width="80px"
        >
          <el-form-item label="用户名">
            <el-input v-model="profileData.username" disabled />
          </el-form-item>
          <el-form-item label="昵称" prop="nickname">
            <el-input v-model="profileData.nickname" placeholder="请输入昵称"/>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 修改密码 -->
      <el-tab-pane label="修改密码" name="password">
        <el-form
          ref="passwordForm"
          :model="passwordData"
          :rules="passwordRules"
          label-width="100px"
        >
          <el-form-item label="原密码" prop="oldPassword">
            <el-input
              v-model="passwordData.oldPassword"
              type="password"
              placeholder="请输入原密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="新密码" prop="newPassword">
            <el-input
              v-model="passwordData.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
            />
          </el-form-item>
          <el-form-item label="确认新密码" prop="confirmPassword">
            <el-input
              v-model="passwordData.confirmPassword"
              type="password"
              placeholder="请再次输入新密码"
              show-password
            />
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <el-button @click="profileDialogVisible = false">取消</el-button>
      <el-button type="primary" @click="submitProfile">确定</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, onMounted, watch, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  Fold, 
  Expand, 
  ArrowDown,
  User,
  SwitchButton
} from '@element-plus/icons-vue'
import Breadcrumb from '@/components/Breadcrumb.vue'
import MenuItem from '@/components/MenuItem.vue'
import { request } from '@/utils/request'

const router = useRouter()
const isCollapse = ref(false)
const activeMenu = ref(router.currentRoute.value.path)
const menus = ref([])
const userInfo = reactive({
  nickname: localStorage.getItem('nickname') || '未知用户'
})

// 表单引用
const profileForm = ref(null)
const passwordForm = ref(null)

// 个人中心相关数据
const profileDialogVisible = ref(false)
const activeTab = ref('info')
const profileData = reactive({
  username: '',
  nickname: ''
})
const passwordData = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单校验规则
const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能小于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordData.newPassword) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const getMenus = async () => {
  try {
    const res = await request('/api/auth/menus')
    if (res.code === 200) {
      menus.value = res.data
    }
  } catch (error) {
    console.error('获取菜单失败:', error)
  }
}

const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      showProfile()
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 显示个人中心
const showProfile = async () => {
  try {
    const res = await request('/api/user/profile')
    if (res.code === 200) {
      profileData.username = res.data.username
      profileData.nickname = res.data.nickname
      profileDialogVisible.value = true
    }
  } catch (error) {
    console.error('获取个人信息失败:', error)
    ElMessage.error(error.message || '获取个人信息失败')
  }
}

// 提交个人信息修改
const submitProfile = async () => {
  if (activeTab.value === 'info') {
    // 提交基本信息
    try {
      await profileForm.value?.validate()
      const res = await request('/api/user/profile', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          username: profileData.username,
          nickname: profileData.nickname
        })
      })
      if (res.code === 200) {
        ElMessage.success('个人信息修改成功')
        profileDialogVisible.value = false
        // 更新显示的昵称
        userInfo.nickname = profileData.nickname
        localStorage.setItem('nickname', profileData.nickname)
      } else {
        ElMessage.error(res.message || '修改失败')
      }
    } catch (error) {
      if (error === false) return // 表单验证失败
      console.error('修改个人信息失败:', error)
      ElMessage.error(error.message || '修改失败')
    }
  } else {
    // 提交密码修改
    try {
      await passwordForm.value?.validate()
      const res = await request('/api/user/password', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          oldPassword: passwordData.oldPassword,
          newPassword: passwordData.newPassword,
          confirmPassword: passwordData.confirmPassword
        })
      })
      if (res.code === 200) {
        ElMessage.success('密码修改成功,请重新登录')
        profileDialogVisible.value = false
        // 清空密码表单
        passwordData.oldPassword = ''
        passwordData.newPassword = ''
        passwordData.confirmPassword = ''
        // 退出登录
        handleLogout()
      } else {
        ElMessage.error(res.message || '修改失败')
      }
    } catch (error) {
      if (error === false) return // 表单验证失败
      console.error('修改密码失败:', error)
      ElMessage.error(error.message || '修改失败')
    }
  }
}

// 处理退出登录
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('nickname')
  router.push('/login')
  ElMessage.success('退出成功')
}

// 切换菜单折叠状态
const toggleCollapse = () => {
  isCollapse.value = !isCollapse.value
}

// 监听路由变化
watch(() => router.currentRoute.value.path, (newPath) => {
  activeMenu.value = newPath
})

// 初始化
onMounted(() => {
  getMenus()
  // 从localStorage获取用户昵称
  userInfo.nickname = localStorage.getItem('nickname')
})

// 获取统计数据
const getStats = async () => {
  try {
    const res = await request('/api/stats')
    if (res.code === 200) {
      stats.value = res.data
    }
  } catch (error) {
    console.error('获取统计数据失败:', error)
  }
}

const handleSelect = (key) => {
  // 处理菜单选择逻辑
}
</script>

<style scoped>
.layout-container {
  height: 100vh;
}

.logo {
  height: 60px;
  line-height: 60px;
  text-align: center;
  border-bottom: 1px solid #dcdfe6;
}

.back-to-nav {
  color: #409EFF;
  font-size: 16px;
  text-decoration: none;
  transition: color 0.3s;
}

.back-to-nav:hover {
  color: #66b1ff;
}

.logo-collapse {
  font-size: 14px;
}

.el-aside {
  background-color: #304156;
  transition: width 0.3s;
  overflow-x: hidden;
}

.el-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  background-color: #fff;
  border-bottom: 1px solid #dcdfe6;
  padding: 0 15px;
}

.header-left {
  display: flex;
  align-items: center;
}

.fold-btn {
  font-size: 20px;
  cursor: pointer;
  margin-right: 15px;
  padding: 0 10px;
}

.fold-btn:hover {
  background: rgba(0,0,0,.025);
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  cursor: pointer;
  padding: 0 8px;
  height: 50px;
}

.user-info:hover {
  background: rgba(0,0,0,.025);
}

.user-avatar {
  background-color: #409EFF;
  color: #fff;
  font-weight: bold;
}

.nickname {
  margin: 0 8px;
  color: #606266;
  font-size: 14px;
}

.el-dropdown-menu {
  padding: 0;
}

.el-dropdown-menu__item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
}

.el-dropdown-menu__item .el-icon {
  margin-right: 8px;
  font-size: 16px;
}

.el-main {
  background-color: #f0f2f5;
  padding: 20px;
}
</style> 